#include "user.h"

#include <QApplication>
#include <QFormLayout>
#include <QGroupBox>
#include <QHBoxLayout>
#include <QSplitter>
#include <QTimer>
#include <QVBoxLayout>

#include "../sql/user_database.h"
#include "ui_user.h"
#include "ui_user_dialog.h"

bool user::m_isLoggedIn = false;
user::user(QWidget *parent) : QWidget(parent), ui(new Ui::user)
{
    ui->setupUi(this);

    // 定时自动退出账户
    m_timer = new QTimer(this);
    m_timer->setSingleShot(true);
    m_timer->setInterval(1000 * 60 * 30);
    connect(m_timer, &QTimer::timeout, this, &user::onLogoutClicked);

    // 连接信号槽
    connect(ui->btn_login, &QPushButton::clicked, this, &user::onLoginClicked);
    connect(ui->btn_logout, &QPushButton::clicked, this, &user::onLogoutClicked);
    connect(ui->btn_add_user, &QPushButton::clicked, this, &user::onAddUserClicked);
    connect(ui->btn_edit, &QPushButton::clicked, this, &user::onEditUserClicked);
    connect(ui->btn_delete, &QPushButton::clicked, this, &user::onDeleteUserClicked);
    connect(ui->btn_reset_password, &QPushButton::clicked, this, &user::onResetPasswordClicked);
    connect(ui->btn_refresh, &QPushButton::clicked, this, &user::onRefreshClicked);
    connect(ui->tableWidget_users, &QTableWidget::itemSelectionChanged, this,
            &user::onTableSelectionChanged);

    // 设置表格
    ui->tableWidget_users->setSelectionBehavior(QAbstractItemView::SelectRows);
    ui->tableWidget_users->setAlternatingRowColors(true);
    ui->tableWidget_users->horizontalHeader()->setStretchLastSection(true);
    ui->tableWidget_users->horizontalHeader()->setDefaultSectionSize(150);

    // 设置Tab顺序
    setTabOrder(ui->lineEdit_username, ui->lineEdit_password);
    setTabOrder(ui->lineEdit_password, ui->btn_login);

    // 设置回车键登录
    ui->lineEdit_username->installEventFilter(this);
    ui->lineEdit_password->installEventFilter(this);

    // 初始化界面
    switchToLoginPage();
}

user::~user() { delete ui; }

bool user::eventFilter(QObject *obj, QEvent *event)
{
    if (event->type() == QEvent::KeyPress) {
        QKeyEvent *keyEvent = static_cast<QKeyEvent *>(event);
        if (keyEvent->key() == Qt::Key_Return || keyEvent->key() == Qt::Key_Enter) {
            if (obj == ui->lineEdit_username || obj == ui->lineEdit_password) {
                if (ui->stackedWidget->currentWidget() == ui->page_login) {
                    onLoginClicked();
                    return true;
                }
            }
        }
    }
    return QWidget::eventFilter(obj, event);
}

void user::onLoginClicked()
{
    QString username = ui->lineEdit_username->text().trimmed();
    QString password = ui->lineEdit_password->text();

    if (username.isEmpty() || password.isEmpty()) {
        QMessageBox::warning(this, "警告", "请输入用户名和密码！");
        return;
    }

    if (validateLogin(username, password)) {
        m_currentUsername = username;
        m_isLoggedIn = true;
        showUserInfo(username);
        switchToManagementPage();
        loadUserList();
        emit currentUserChanged(username);
    } else {
        QMessageBox::critical(this, "错误", "用户名或密码错误！");
        ui->lineEdit_password->clear();
    }
}

void user::onLogoutClicked()
{
    m_currentUsername.clear();
    m_currentUserRole.clear();
    m_isLoggedIn = false;

    ui->lineEdit_username->clear();
    ui->lineEdit_password->clear();
    emit currentUserChanged("未登录");
    switchToLoginPage();
}

void user::onAddUserClicked()
{
    if (m_currentUserRole != "admin") {
        QMessageBox::warning(this, "权限不足", "只有管理员才能添加用户！");
        return;
    }

    UserDialog dialog(UserDialog::AddMode, this);
    if (dialog.exec() == QDialog::Accepted) {
        UserInfo newUser(dialog.getUsername(), dialog.getPassword(), dialog.getRole(),
                         dialog.getIsActive() ? "启用" : "禁用");

        if (UserDatabase::addUser(newUser)) {
            QMessageBox::information(this, "成功", "用户添加成功！");
            loadUserList();
        } else {
            QMessageBox::critical(this, "错误", "用户添加失败！可能用户名已存在。");
        }
    }
}

void user::onEditUserClicked()
{
    if (m_currentUserRole != "admin") {
        QMessageBox::warning(this, "权限不足", "只有管理员才能编辑用户！");
        return;
    }

    int currentRow = ui->tableWidget_users->currentRow();
    if (currentRow < 0) {
        QMessageBox::warning(this, "提示", "请选择要编辑的用户！");
        return;
    }

    QString username = ui->tableWidget_users->item(currentRow, 1)->text();
    QString role = ui->tableWidget_users->item(currentRow, 2)->text();
    QString status = ui->tableWidget_users->item(currentRow, 5)->text();
    bool isActive = (status == "启用");

    UserDialog dialog(UserDialog::EditMode, this);
    dialog.setUserData(username, role, isActive);

    if (dialog.exec() == QDialog::Accepted) {
        UserInfo updatedUser;
        updatedUser.username = username;
        updatedUser.role = dialog.getRole();
        updatedUser.status = dialog.getIsActive() ? "启用" : "禁用";

        // 如果输入了新密码，则更新密码
        if (!dialog.getPassword().isEmpty()) {
            updatedUser.setPassword(dialog.getPassword());
        }

        if (UserDatabase::updateUser(updatedUser)) {
            QMessageBox::information(this, "成功", "用户信息更新成功！");
            loadUserList();
        } else {
            QMessageBox::critical(this, "错误", "用户信息更新失败！");
        }
    }
}

void user::onDeleteUserClicked()
{
    if (m_currentUserRole != "admin") {
        QMessageBox::warning(this, "权限不足", "只有管理员才能删除用户！");
        return;
    }

    int currentRow = ui->tableWidget_users->currentRow();
    if (currentRow < 0) {
        QMessageBox::warning(this, "提示", "请选择要删除的用户！");
        return;
    }

    QString username = ui->tableWidget_users->item(currentRow, 1)->text();

    if (username == m_currentUsername) {
        QMessageBox::warning(this, "错误", "不能删除当前登录的用户！");
        return;
    }

    int ret = QMessageBox::question(
        this, "确认删除", QString("确定要删除用户 \"%1\" 吗？此操作不可恢复！").arg(username),
        QMessageBox::Yes | QMessageBox::No);

    if (ret == QMessageBox::Yes) {
        if (UserDatabase::deleteUser(username)) {
            QMessageBox::information(this, "成功", "用户删除成功！");
            loadUserList();
        } else {
            QMessageBox::critical(this, "错误", "用户删除失败！");
        }
    }
}

void user::onResetPasswordClicked()
{
    if (m_currentUserRole != "admin") {
        QMessageBox::warning(this, "权限不足", "只有管理员才能重置密码！");
        return;
    }

    int currentRow = ui->tableWidget_users->currentRow();
    if (currentRow < 0) {
        QMessageBox::warning(this, "提示", "请选择要重置密码的用户！");
        return;
    }

    QString username = ui->tableWidget_users->item(currentRow, 1)->text();

    bool ok;
    QString newPassword =
        QInputDialog::getText(this, "重置密码", QString("为用户 \"%1\" 设置新密码:").arg(username),
                              QLineEdit::Password, "", &ok);

    if (ok && !newPassword.isEmpty()) {
        if (UserDatabase::resetPassword(username, newPassword)) {
            QMessageBox::information(this, "成功", "密码重置成功！");
        } else {
            QMessageBox::critical(this, "错误", "密码重置失败！");
        }
    }
}

void user::onRefreshClicked() { loadUserList(); }

void user::onTableSelectionChanged() { updateUserButtonStates(); }

void user::showEvent(QShowEvent *event)
{
    QWidget::showEvent(event);

    if (m_timer && m_isLoggedIn) {
        m_timer->stop();
    }
}
void user::hideEvent(QHideEvent *event)
{
    QWidget::hideEvent(event);
    // 定时自动退出账户
    if (m_timer && m_isLoggedIn) {
        m_timer->start();
    }
}
void user::switchToLoginPage()
{
    ui->stackedWidget->setCurrentWidget(ui->page_login);

    // 显示最后登录的用户名
    QString lastUsername = UserDatabase::getLastLoginUsername();
    if (!lastUsername.isEmpty()) {
        ui->lineEdit_username->setText(lastUsername);
        ui->lineEdit_password->setFocus();  // 焦点设置到密码框
    } else {
        ui->lineEdit_username->setFocus();  // 如果没有历史用户名，焦点设置到用户名框
    }
}

void user::switchToManagementPage() { ui->stackedWidget->setCurrentWidget(ui->page_management); }

void user::loadUserList()
{
    ui->tableWidget_users->setRowCount(0);

    QVector<UserInfo> users = UserDatabase::getAllUsers();

    for (const UserInfo &userInfo : users) {
        int row = ui->tableWidget_users->rowCount();
        ui->tableWidget_users->insertRow(row);

        // ID
        QTableWidgetItem *idItem = new QTableWidgetItem(QString::number(userInfo.id));
        idItem->setTextAlignment(Qt::AlignCenter);
        idItem->setFlags(idItem->flags() & ~Qt::ItemIsEditable);
        ui->tableWidget_users->setItem(row, 0, idItem);

        // 用户名
        QTableWidgetItem *usernameItem = new QTableWidgetItem(userInfo.username);
        usernameItem->setTextAlignment(Qt::AlignCenter);
        usernameItem->setFlags(usernameItem->flags() & ~Qt::ItemIsEditable);
        ui->tableWidget_users->setItem(row, 1, usernameItem);

        // 角色
        QTableWidgetItem *roleItem = new QTableWidgetItem(userInfo.role);
        roleItem->setTextAlignment(Qt::AlignCenter);
        roleItem->setFlags(roleItem->flags() & ~Qt::ItemIsEditable);
        ui->tableWidget_users->setItem(row, 2, roleItem);

        // 创建时间
        QTableWidgetItem *createTimeItem =
            new QTableWidgetItem(userInfo.createTime.toString("yyyy-MM-dd hh:mm:ss"));
        createTimeItem->setTextAlignment(Qt::AlignCenter);
        createTimeItem->setFlags(createTimeItem->flags() & ~Qt::ItemIsEditable);
        ui->tableWidget_users->setItem(row, 3, createTimeItem);

        // 最后登录时间
        QString lastLoginText = userInfo.lastLoginTime.isValid()
                                    ? userInfo.lastLoginTime.toString("yyyy-MM-dd hh:mm:ss")
                                    : "从未登录";
        QTableWidgetItem *lastLoginItem = new QTableWidgetItem(lastLoginText);
        lastLoginItem->setTextAlignment(Qt::AlignCenter);
        lastLoginItem->setFlags(lastLoginItem->flags() & ~Qt::ItemIsEditable);
        ui->tableWidget_users->setItem(row, 4, lastLoginItem);

        // 状态
        QTableWidgetItem *statusItem = new QTableWidgetItem(userInfo.status);
        statusItem->setTextAlignment(Qt::AlignCenter);
        statusItem->setFlags(statusItem->flags() & ~Qt::ItemIsEditable);
        ui->tableWidget_users->setItem(row, 5, statusItem);
    }

    updateUserButtonStates();
}

void user::updateUserButtonStates()
{
    bool hasSelection = ui->tableWidget_users->currentRow() >= 0;
    bool isAdmin = (m_currentUserRole == "admin");

    ui->btn_edit->setEnabled(hasSelection && isAdmin);
    ui->btn_delete->setEnabled(hasSelection && isAdmin);
    ui->btn_reset_password->setEnabled(hasSelection && isAdmin);
    ui->btn_add_user->setEnabled(isAdmin);
}

bool user::validateLogin(const QString &username, const QString &password)
{
    UserInfo userInfo = UserDatabase::validateUser(username, password);
    if (userInfo.id != -1 && userInfo.isActive()) {
        m_currentUserRole = userInfo.role;
        return true;
    }

    return false;
}

void user::showUserInfo(const QString &username)
{
    ui->label_current_user->setText(
        QString("当前用户: %1 (%2)").arg(username).arg(m_currentUserRole));
}

// ========== UserDialog 实现 ==========

UserDialog::UserDialog(Mode mode, QWidget *parent)
    : QDialog(parent), ui(new Ui::UserDialog), m_mode(mode)
{
    ui->setupUi(this);

    if (mode == AddMode) {
        setWindowTitle("添加用户");
    } else {
        setWindowTitle("编辑用户");
        // 编辑模式时禁用用户名输入
        ui->lineEdit_username->setEnabled(false);
    }

    connect(ui->buttonBox, &QDialogButtonBox::accepted, this, &UserDialog::onAccepted);
    connect(ui->buttonBox, &QDialogButtonBox::rejected, this, &QDialog::reject);
}

UserDialog::~UserDialog() { delete ui; }

void UserDialog::setUserData(const QString &username, const QString &role, bool isActive)
{
    ui->lineEdit_username->setText(username);

    int roleIndex = ui->comboBox_role->findText(role);
    if (roleIndex >= 0) {
        ui->comboBox_role->setCurrentIndex(roleIndex);
    }

    ui->comboBox_status->setCurrentIndex(isActive ? 0 : 1);

    // 编辑模式时不需要输入密码
    if (m_mode == EditMode) {
        ui->lineEdit_password->setPlaceholderText("留空保持原密码不变");
        ui->lineEdit_confirm_password->setPlaceholderText("留空保持原密码不变");
    }
}

QString UserDialog::getUsername() const { return ui->lineEdit_username->text().trimmed(); }

QString UserDialog::getPassword() const { return ui->lineEdit_password->text(); }

QString UserDialog::getRole() const { return ui->comboBox_role->currentText(); }

bool UserDialog::getIsActive() const { return ui->comboBox_status->currentIndex() == 0; }

void UserDialog::onAccepted()
{
    if (validateInput()) {
        accept();
    }
}

bool UserDialog::validateInput()
{
    QString username = getUsername();
    QString password = getPassword();
    QString confirmPassword = ui->lineEdit_confirm_password->text();

    if (username.isEmpty()) {
        QMessageBox::warning(this, "错误", "请输入用户名！");
        ui->lineEdit_username->setFocus();
        return false;
    }

    if (m_mode == AddMode && password.isEmpty()) {
        QMessageBox::warning(this, "错误", "请输入密码！");
        ui->lineEdit_password->setFocus();
        return false;
    }

    if (!password.isEmpty() && password != confirmPassword) {
        QMessageBox::warning(this, "错误", "两次输入的密码不一致！");
        ui->lineEdit_confirm_password->setFocus();
        return false;
    }

    if (!password.isEmpty() && password.length() < 4) {
        QMessageBox::warning(this, "错误", "密码长度至少4位!");
        ui->lineEdit_password->setFocus();
        return false;
    }

    return true;
}
